package org.java.user.service;

import org.java.commons.vo.Result;
import org.java.user.api.domain.Role;
import org.java.user.api.domain.User;
import org.java.user.repository.RoleRepository;
import org.java.user.repository.UserRepository;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService, InitializingBean {

    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void afterPropertiesSet() throws Exception {
        charAndInitDefaultRoles();
    }
//  检查并初始化默认角色
    private void charAndInitDefaultRoles() {
//   查询roleKey是否为ADMIN,不存在则增加，并且builtIn为true、fixed为false。
    roleRepository.findByRoleKey("ADMIN")
        .ifPresentOrElse((role)->{
//            当角色存在时
        },()->{
//            当角色不存在时
            Role role = new Role();
            role.setName("管理员");
            role.setRoleKey("ADMIN");
            role.setFixed(false);
            role.setBuiltIn(true);
            this.roleRepository.save(role);
        });

//    查询roleKey是否为User，不存在则新增一条，并且builtIn和fixed都为true。
        roleRepository.findByRoleKey("USER")
        .ifPresentOrElse((role)->{

        },()->{
            Role role = new Role();
            role.setBuiltIn(true);
            role.setFixed(true);
            role.setName("用户");
            role.setRoleKey("USER");
            this.roleRepository.save(role);
        });

    }

    @Override
    public Result registry(User user) {
//        1、检查登录名是否被占用
        Optional<User>optionalUser=this.userRepository.findByLoginName(user.getLoginName());
        if (optionalUser.isPresent()){
            return Result.error("登录名已经存在！");
        }
//        2、查询固定内置角色，添加给user对象
        List<Role> roles = this.roleRepository.findByBuiltInIsTrueAndFixedIsTrue();
        user.setRoles(roles);
//        保存用户信息到数据库
        String password = user.getPassword();
        password = this.passwordEncoder.encode(password);
        user.setPassword(password);

        this.userRepository.save(user);
        return Result.ok("注册成功");
    }

    @Override
    public User loadUserByName(String name) {
//        判断用哪种方式查询
        User user = this.userRepository.findByLoginName(name).orElse(null);
        if(user==null){
            user=this.userRepository.findByMobilePhone(name).orElse(null);
        }
        if (user==null){
            user=this.userRepository.findByEmail(name).orElse(null);
        }
        return user;
    }
}
